package com.chaodev.base.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.chaodev.base.model.*;
import com.chaodev.base.base.RedisDao;
import com.chaodev.base.dto.DepartDTO;
import com.chaodev.base.dto.QueryDto;
import com.chaodev.base.service.IDepartService;
import com.chaodev.base.service.ILogService;
import com.chaodev.base.utils.JwtUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@SuppressWarnings("all")
@RequestMapping(value = "/org")
public class DepartController {
    @Autowired
    private RedisDao redisDao;

    @Autowired
    private ILogService logService;

    @Autowired
    private IDepartService departService;

    @Value("${myserver.name}")
    private String myserverName;

    @Value("${platform}")
    private String platform;

    /**
     * @Description: 获取部门树
     * @Author: xy
     * @CreateDate: 2019/12/27 11:09
     * @UpdateUser: xy
     * @UpdateDate: 2019/12/27 11:09
     * @UpdateRemark: 修改内容
     * @Version: 1.0
     */
    @PostMapping(value = "/getOrgOptions")
    @ResponseBody
    @SuppressWarnings("ALL")
    @ApiOperation(value = "获取部门树")
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result getDepartTree(@RequestBody @ApiParam(value = "节点信息") Tree tree, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            Map<String, Object> map = new HashMap<>();
            map.put("P_TYPE", "");
            map.put("P_DEPART_ID", "");
            //用户自身的部门id
            if(StrUtil.isEmpty(tree.getCurrnode())){
                map.put("U_DEPART_ID", userInfo.getDepartId());
            }else{
                map.put("U_DEPART_ID", tree.getCurrnode());
            }

            List<Map<String, Object>> list = departService.getDepartTree(map);
            Iterator<Map<String, Object>> it = list.iterator();
            List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
            while (it.hasNext()) {
                Map<String, Object> resultMap = it.next();
                Map<String, Object> dataMap = new HashMap<>();
                if (resultMap.get("NODE_ID").toString().equals(userInfo.getDepartId())) {
                    dataMap.put("value", resultMap.get("NODE_ID") == null ? "" : resultMap.get("NODE_ID").toString());
                    dataMap.put("label", resultMap.get("TEXT_NAME") == null ? "" : resultMap.get("TEXT_NAME").toString());
                    String nodeid = resultMap.get("NODE_ID") == null ? "" : resultMap.get("NODE_ID").toString();
                    List<Map<String, Object>> listChild = new ArrayList<>();
                    if (resultMap.get("STATE").equals("closed")) {
                        listChild = GetChildMap(nodeid, list);
                    }
                    dataMap.put("children", listChild);
                    resultList.add(dataMap);
                }
            }
            result.setCode(ResultEnum.SUCCESS.getCode());
            result.setData(resultList);

            Result logResult = new Result();
            logResult.setCode(0);
            logResult.setMsg("数据获取成功");//不记录返回数据，只做标识
            logResult.setServerID(result.getServerID());
            logService.logAdd(tree.toString(), "获取部门树", "SUCCESS", logResult.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(tree.toString(), "获取部门树", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }

    public List<Map<String, Object>> GetChildMap(String PID, List<Map<String, Object>> list) {
        List<Map<String, Object>> listChild = new ArrayList<>();
        for (Map<String, Object> listChildMap : list) {
            if (listChildMap.get("pid").toString().equals(PID)) {
                Map<String, Object> dataMap1 = new HashMap<>();
                dataMap1.put("value", listChildMap.get("NODE_ID") == null ? "" : listChildMap.get("NODE_ID").toString());
                dataMap1.put("label", listChildMap.get("TEXT_NAME") == null ? "" : listChildMap.get("TEXT_NAME").toString());
                if(listChildMap.containsKey("pid")){
                    dataMap1.put("pid",listChildMap.get("pid").toString());
                }
                if(listChildMap.containsKey("departName")){
                    dataMap1.put("departName",listChildMap.get("departName").toString());
                }
                if(listChildMap.containsKey("roleName")){
                    dataMap1.put("roleName",listChildMap.get("roleName").toString());
                }
                if(listChildMap.containsKey("type")){
                    dataMap1.put("type",listChildMap.get("type").toString());
                }
                if(listChildMap.containsKey("level")){
                    dataMap1.put("level",listChildMap.get("level").toString());
                }
                List<Map<String, Object>> listChildnew = new ArrayList<>();
                if (listChildMap.get("STATE").equals("closed")) {
                    listChildnew = GetChildMap(listChildMap.get("NODE_ID").toString(), list);
                }
                dataMap1.put("children", listChildnew);
                listChild.add(dataMap1);
            }
        }
        return listChild;
    }

    /**
     * @Description: 获取部门列表
     * @Author: xy
     * @CreateDate: 2019/12/27 11:09
     * @UpdateUser: xy
     * @UpdateDate: 2019/12/27 11:09
     * @UpdateRemark: 修改内容
     * @Version: 1.0
     */
    @PostMapping(value = "/getOrgList")
    @ApiOperation(value = "获取部门列表")
    @ResponseBody
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result departQuery(@RequestBody @ApiParam(value = "分页传入参数") DataPageVO dataPage, HttpServletRequest request, HttpServletResponse response) {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            if (null == dataPage.getPage()) {
                dataPage.setPage(1);
            }
            if (null == dataPage.getRows()) {
                dataPage.setRows(20);
            }
            Map<String, Object> map = new HashMap<>();
            map.put("P_PAGE", dataPage.getPage());
            map.put("P_PAGESIZE", dataPage.getRows());
            map.put("P_KEYWORD", dataPage.getKeyword());
            map.put("P_SORTNAME", dataPage.getSort());
            map.put("P_SORTORDER", dataPage.getOrder());
            map.put("P_USERID", userInfo.getUserId());
            map.put("U_DEPART_ID", userInfo.getDepartId());
            map.put("V_KEYWORD",dataPage.getKeyword());
            PageInfo<DepartDTO> departDTOPageInfo = departService.departQuery(map);
            result.setCode(0);

            Map<String, Object> mapnew = new HashMap<>();
            mapnew.put("total", departDTOPageInfo.getTotal());
            mapnew.put("rows", departDTOPageInfo.getList());
            result.setCode(ResultEnum.SUCCESS.getCode());
            result.setData(mapnew);

            Result logResult = new Result();
            logResult.setCode(0);
            logResult.setMsg("数据获取成功");//不记录返回数据，只做标识
            logResult.setServerID(result.getServerID());
            logService.logAdd(dataPage.toString(), "获取部门列表", "SUCCESS", logResult.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(dataPage.toString(), "获取部门列表", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }

    @PostMapping(value = "/save")
    @ResponseBody
    @ApiOperation(value = "新增/编辑部门")
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    @Transactional(rollbackFor = Exception.class)
    public Result departAdd(@RequestBody @ApiParam(value = "部门信息") Depart depart, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            //处理成功或失败标志
            boolean flag = false;
            //获取departLevel和parentDepartIds
            Depart newDepart = departService.getDepartAddLevelAndParentIds(depart);
            depart.setDepartLevel(newDepart.getDepartLevel());
            //判断是新增操作还是修改操作
            if (null != depart.getDepartId() && !"".equals(depart.getDepartId())) {
                //修改操作
                flag = departService.departUpd(depart);
            } else {
                //新增操作
                depart.setCreateUser(userInfo.getUserId());

                //先插入并返回主键
                if("mysql".equals(platform)){
                    flag = departService.departAddMysql(depart);
                }
                if("oracle".equals(platform)){
                    flag = departService.departAddOracle(depart);
                }
                //更新parentDepartIds
                if (flag) {
                    //对于mysql才去更新parentDepartIds
                    if ("mysql".equals(platform)) {
                        Depart updDepart = new Depart();
                        if (null != newDepart.getParentDepartIds() && !"".equals(newDepart.getParentDepartIds())) {
                            StringBuilder parentDepartIds = new StringBuilder();
                            parentDepartIds.append(newDepart.getParentDepartIds()).append(",").append(depart.getDepartId());
                            updDepart.setParentDepartIds(parentDepartIds.toString());
                        }
                        updDepart.setDepartId(String.valueOf(depart.getDepartId()));
                        departService.departUpd(updDepart);
                    }
                }
            }
            if (flag) {
                result.setCode(ResultEnum.SUCCESS.getCode());
                result.setMsg("提交成功");
            } else {
                result.setCode(-1);
                result.setMsg("提交失败");
            }
            logService.logAdd(depart.toString(), "新增/编辑部门", "SUCCESS", result.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(depart.toString(), "新增/编辑部门", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }

    /**
     * @Description: 部门删除
     * @Author: xy
     * @CreateDate: 2019/12/27 11:17
     * @UpdateUser: xy
     * @UpdateDate: 2019/12/27 11:17
     * @UpdateRemark: 修改内容
     * @Version: 1.0
     */
    @PostMapping(value = "/delete")
    @ResponseBody
    @SuppressWarnings("all")
    @ApiOperation(value = "删除部门")
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result departDelete(@RequestBody @ApiParam(value = "部门信息") Depart depart, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            boolean flag = departService.departDelete(depart);
            if (flag) {
                result.setCode(ResultEnum.SUCCESS.getCode());
                result.setMsg("删除成功");
            } else {
                result.setCode(-1);
                result.setMsg("删除失败");
            }
            logService.logAdd(depart.toString(), "删除部门", "SUCCESS", result.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(depart.toString(), "删除部门", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }

    /**
     * @Description: 获取用户管理架构树
     * @Author: xy
     * @CreateDate: 2019/12/27 14:33
     * @UpdateUser: xy
     * @UpdateDate: 2019/12/27 14:33
     * @UpdateRemark: 修改内容
     * @Version: 1.0
     */
    @RequestMapping(value = "/getOrgZtree", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "获取用户管理架构树")
    @SuppressWarnings("all")
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public List<DepartDTO> getOrgZtree(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> map = new HashMap<>();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        List<DepartDTO> list = new ArrayList<>();
        Result logResult = new Result();
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            map.put("P_DEPART_ID", userInfo.getDepartId());
            list = departService.getMenuZtree(map);
            logResult.setCode(0);
            //不记录返回数据，只做标识
            logResult.setMsg("数据获取成功");
            logService.logAdd("", "获取用户管理架构树", "SUCCESS", logResult.toString(), userInfo, request);
        } else {
            logResult.setCode(-1);
            //不记录返回数据，只做标识
            logResult.setMsg("数据获取失败");
            logService.logAdd("", "获取用户管理架构树", "ERROR", logResult.toString(), userInfo, request);
        }
        return list;
    }

    @PostMapping(value = "/getDepartList")
    @ResponseBody
    @SuppressWarnings("all")
    @ApiOperation(value = "获取部门列表")
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result getDepartList(@RequestBody DataPageVO dto, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            PageHelper.startPage(dto.getPage(),dto.getRows());
            List<Depart> departList = departService.getDepartList(dto.getDepartId());
            PageInfo<Depart> pageInfo=new PageInfo<>(departList,dto.getRows());
            result.setCode(ResultEnum.SUCCESS.getCode());
            result.setData(pageInfo);
            result.setMsg("获取数据成功");

            logService.logAdd(dto.toString(), "获取部门列表", "SUCCESS", result.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(dto.toString(), "获取部门列表", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }

    /**
     * @Description: 获取部门树
     * @Author: xy
     * @CreateDate: 2019/12/27 11:09
     * @UpdateUser: xy
     * @UpdateDate: 2019/12/27 11:09
     * @UpdateRemark: 修改内容
     * @Version: 1.0
     */
    @PostMapping(value = "/getOrgAndUserTree")
    @ResponseBody
    @SuppressWarnings("ALL")
    @ApiOperation(value = "获取部门和人员树")
    @ApiImplicitParam(name = "token", paramType = "header", value = "token", dataType = "string", required = true)
    public Result getOrgAndUserTree(@RequestBody @ApiParam(value = "节点信息") QueryDto tree, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Result result = new Result();
        String token = request.getHeader("token");
        UserInfo userInfo = new UserInfo();
        if (redisDao.existsKey(token)) {
            userInfo = JwtUtil.getUserInfoFromToken(token, redisDao);
            Map<String, Object> map = new HashMap<>();
            map.put("name", tree.getName());
            //用户自身的部门id
            if(!StrUtil.isEmpty(tree.getNodeId())){
                map.put("pid", tree.getNodeId());
            }

            List<Map<String, Object>> list = departService.getDepartAndUserTree(map);

            Iterator<Map<String, Object>> it = list.iterator();
            List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
            while (it.hasNext()) {
                Map<String, Object> resultMap = it.next();
                Map<String, Object> dataMap = new HashMap<>();
                if (resultMap.get("NODE_ID").toString().equals("0")) {
                    dataMap.put("value", resultMap.get("NODE_ID") == null ? "" : resultMap.get("NODE_ID").toString());
                    dataMap.put("label", resultMap.get("TEXT_NAME") == null ? "" : resultMap.get("TEXT_NAME").toString());
                    dataMap.put("pid", resultMap.get("pid") == null ? "" : resultMap.get("pid").toString());
                    dataMap.put("departName", resultMap.get("departName") == null ? "" : resultMap.get("departName").toString());
                    dataMap.put("roleName", resultMap.get("roleName") == null ? "" : resultMap.get("roleName").toString());
                    dataMap.put("type", resultMap.get("type") == null ? "" : resultMap.get("type").toString());
                    dataMap.put("level", resultMap.get("level") == null ? "" : resultMap.get("level").toString());
                    String nodeid = resultMap.get("NODE_ID") == null ? "" : resultMap.get("NODE_ID").toString();
                    List<Map<String, Object>> listChild = new ArrayList<>();
                    if (resultMap.get("STATE").equals("closed")) {
                        listChild = GetChildMap(nodeid, list);
                    }
                    dataMap.put("children", listChild);
                    resultList.add(dataMap);
                }
            }
            if(CollUtil.isEmpty(resultList)){
                List<Object> collect = list.stream().filter(d -> d.get("type").equals("org")).
                        map(e -> e.get("level")).distinct().sorted().collect(Collectors.toList());
                List<Map<String, Object>> list1;
                for (Object o : collect) {
                    list1 = list.stream().filter(c -> c.get("level").equals(o)).collect(Collectors.toList());
                    if(list1.size()>0) {
                        Iterator<Map<String, Object>> it1 = list1.iterator();
                        while (it1.hasNext()) {
                            Map<String, Object> resultMap = it1.next();
                            Map<String, Object> dataMap = new HashMap<>();
                            dataMap.put("value", resultMap.get("NODE_ID") == null ? "" : resultMap.get("NODE_ID").toString());
                            dataMap.put("label", resultMap.get("TEXT_NAME") == null ? "" : resultMap.get("TEXT_NAME").toString());
                            dataMap.put("pid", resultMap.get("pid") == null ? "" : resultMap.get("pid").toString());
                            dataMap.put("departName", resultMap.get("departName") == null ? "" : resultMap.get("departName").toString());
                            dataMap.put("roleName", resultMap.get("roleName") == null ? "" : resultMap.get("roleName").toString());
                            dataMap.put("type", resultMap.get("type") == null ? "" : resultMap.get("type").toString());
                            dataMap.put("level", resultMap.get("level") == null ? "" : resultMap.get("level").toString());
                            String nodeid = resultMap.get("NODE_ID") == null ? "" : resultMap.get("NODE_ID").toString();
                            List<Map<String, Object>> listChild = new ArrayList<>();
                            if (resultMap.get("STATE").equals("closed")) {
                                listChild = GetChildMap(nodeid, list);
                            }
                            dataMap.put("children", listChild);

                            List<Object> children = resultList.stream()
                                    .map(e -> e.get("children"))
                                    .collect(Collectors.toList());
//                            if(resultList.stream().filter(d->d.get("value").equals(nodeid)).count()==0&&
//                                    children.stream().filter(e->e.get("value").equals(nodeid)).count()==0)
//                            children.stream().map(d-> JSONArray.parse(d.toString())).forEach(e-> System.out.println("e = " + e));
                            if(!CollUtil.contains(resultList,nodeid)&&!CollUtil.contains(children,nodeid)){
                                resultList.add(dataMap);
                            }
                        }
                    }
                }

            }
//            System.out.println("resultList = " + resultList);
            result.setCode(ResultEnum.SUCCESS.getCode());
            result.setData(resultList);

            Result logResult = new Result();
            logResult.setCode(0);
            logResult.setMsg("数据获取成功");//不记录返回数据，只做标识
            logResult.setServerID(result.getServerID());
            logService.logAdd(tree.toString(), "获取部门树", "SUCCESS", logResult.toString(), userInfo, request);
        } else {
            result.setCode(-1);
            result.setMsg("登录超时");
            logService.logAdd(tree.toString(), "获取部门树", "ERROR", result.toString(), userInfo, request);
        }
        return result;
    }
}
